/**
 * Copyright (C), 2015-2020, XXX有限公司
 * FileName: TripPlanActivity
 * Author: Clark
 * Date: 2020/10/8 16:34
 * Description:
 * History:
 * <author> <time> <version> <desc>
 * 作者姓名 修改时间 版本号 描述
 */
package sz.szsmk.citizencard.ui.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.DefaultLayoutHelper;
import com.chenenyu.router.annotation.Route;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import kotlin.jvm.Synchronized;
import sz.szsmk.citizencard.DaggerApplication;
import sz.szsmk.citizencard.R;
import sz.szsmk.citizencard.databinding.ActivityTripPlanMainBinding;
import sz.szsmk.citizencard.ioc.Compontent.DaggerCommonActivityComponent;
import sz.szsmk.citizencard.model.network.bean.StationNearBean;
import sz.szsmk.citizencard.model.network.bean.response.QueryNearMetroStandbyRes;
import sz.szsmk.citizencard.model.network.bean.response.QueryNearStandbyRes;
import sz.szsmk.citizencard.model.network.dzbean.res.MessageEvent;
import sz.szsmk.citizencard.mvp.contract.ITripPlanContact;
import sz.szsmk.citizencard.mvp.presenter.ItripPlanPresenter;
import sz.szsmk.citizencard.ui.adapter.TripPlanBusAdapter;
import sz.szsmk.citizencard.ui.adapter.TripPlanBusListAdapter;
import sz.szsmk.citizencard.ui.adapter.TripPlanStationListAdapter;
import sz.szsmk.citizencard.ui.adapter.TripPlanSubwayAdapter;
import sz.szsmk.citizencard.ui.base.IBaseActivity;
import sz.szsmk.citizencard.ui.newversion.config.Constants;
import sz.szsmk.citizencard.util.AMapUtil;
import sz.szsmk.citizencard.util.Constant;
import sz.szsmk.citizencard.util.JumpThirdView;
import sz.szsmk.citizencard.util.JumpUtils;
import sz.szsmk.citizencard.util.PermissionUtil;
import sz.szsmk.citizencard.util.StringUtils;
import sz.szsmk.citizencard.util.Utils;

/**
 * @ClassName: TripPlanActivity
 * @Description:
 * @Author: Clark
 * @Date: 2020/10/8 16:34
 */
@Route("tripPlan")
public
class TripPlanActivity extends IBaseActivity<ItripPlanPresenter, ActivityTripPlanMainBinding>
        implements ITripPlanContact.ITripPlanView, View.OnClickListener {
    private RecyclerView mainView;
    TripPlanBusAdapter tripPlanBusAdapter;
    TripPlanSubwayAdapter tripPlanSubwayAdapter;
    TripPlanStationListAdapter tripPlanStationListAdapter;
    VirtualLayoutManager layoutManager; //alibaba VLayout
    private DelegateAdapter delegateAdapter;
    private LinkedList<DelegateAdapter.Adapter> adapters;
    private SwipeRefreshLayout swipeRefreshLayout;
    private int metroNum;
    private List<StationNearBean> listStationNear=new ArrayList<>();
    private boolean dataEmpty=true;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_trip_plan_main;
    }

    @Override
    protected void initInjector() {
        DaggerCommonActivityComponent.builder().appCompontent(DaggerApplication.getAppComponent()).build().inject(this);

    }

    @Override
    protected void initViews() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            PermissionUtil.checkPermission(this, Manifest.permission.ACCESS_FINE_LOCATION,getResources().getString(R.string.location_permission));
        }

        swipeRefreshLayout = dataBinding.swipeRefreshLayout;
        swipeRefreshLayout.setEnabled(false);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mPresenter.getBusNearStation();
                mPresenter.getSubwayNearStation();
            }
        });
        mainView = dataBinding.tripView;
        layoutManager = new VirtualLayoutManager(TripPlanActivity.this) {

            @Override
            public boolean canScrollVertically() {
                return true;
            }
        };
        dataBinding.back.settingTitle.setText(getString(R.string.trip_plan));

        mainView.setLayoutManager(layoutManager);
        mainView.setNestedScrollingEnabled(false);
        mainView.setHasFixedSize(true);
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        mainView.setRecycledViewPool(viewPool);
        viewPool.setMaxRecycledViews(0, 30);
        delegateAdapter = new DelegateAdapter(layoutManager, true);
        mainView.setAdapter(delegateAdapter);
        adapters = new LinkedList<>();
        DefaultLayoutHelper defaultLayoutHelperHelper = new DefaultLayoutHelper();
        tripPlanSubwayAdapter = new TripPlanSubwayAdapter(getActivity(), defaultLayoutHelperHelper);
        tripPlanSubwayAdapter.setBaseInterface(new TripPlanSubwayAdapter.BaseInterface() {
            @Override
            public void onClick(View view, QueryNearMetroStandbyRes.MetroSiteListBean bean) {
                //点击事件处理
                Log.d("clark", view.getId()+"");
                int id = view.getId();
                if (id == R.id.subway_station_go) {
                    Utils.startMapBylocationByBaiduCorSys(TripPlanActivity.this, bean.getLatitude(), bean.getLongitude(), bean.getStandName());
                } else if (id == R.id.item_layout) {
                    Bundle bundle = new Bundle();
                    bundle.putString("type", bean.getStandName() + "");
                    bundle.putString("from", "tripPlan");
                    JumpUtils.jumptoNatvie(TripPlanActivity.this, "SubwaySiteDetailActivity", 0, bundle);
                }


//                if (AMapUtil.isInstallByRead("com.autonavi.minimap")) {
//                    Log.d("clark", "trip plan click metro");
//                    AMapUtil.goToNaviActivity(TripPlanActivity.this, "test", null, bean.getLatitude() + "", bean.getLongitude() + "", "1", "2");
//                } else {
//                    Toast.makeText(TripPlanActivity.this, "请到应用市场下载高德地图", Toast.LENGTH_LONG).show();
//                }
            }
        });
        adapters.add(tripPlanSubwayAdapter);
        tripPlanBusAdapter = new TripPlanBusAdapter(getActivity(), defaultLayoutHelperHelper, tripPlanSubwayAdapter.getNum());
        tripPlanBusAdapter.setBaseInterface(new TripPlanBusAdapter.BaseInterface() {
            @Override
            public void onClick(View view, QueryNearStandbyRes.BusSiteListBean bean) {
                //点击处理事件\
//                if (AMapUtil.isInstallByRead("com.autonavi.minimap")) {
//                    Log.d("clark", "trip plan click bus");
//
//                    AMapUtil.goToNaviActivity(TripPlanActivity.this, "test", null, bean.getLatitude() + "", bean.getLongitude() + "", "1", "2");
//                } else {
//                    Toast.makeText(TripPlanActivity.this, "请到应用市场下载高德地图", Toast.LENGTH_LONG).show();
//                }
                Bundle bundle = new Bundle();
                bundle.putString("stand_name",bean.getStand_name());
                bundle.putString("stand_guid",bean.getStand_guid());
                JumpUtils.jumptoNatvie(TripPlanActivity.this, "BusSiteDetailActivity", 0,bundle);

            }
        });

        adapters.add(tripPlanBusAdapter);


        delegateAdapter.setAdapters(adapters);
//        delegateAdapter.notifyDataSetChanged();
        dataBinding.back.back.setOnClickListener(this);
        dataBinding.tripDes.setOnClickListener(this);
        dataBinding.tripMetro.setOnClickListener(this);
        dataBinding.tripBus.setOnClickListener(this);
        dataBinding.tripCollect.setOnClickListener(this);

        tripPlanStationListAdapter = new TripPlanStationListAdapter(this);
        tripPlanStationListAdapter.setBaseInterface(new TripPlanStationListAdapter.BaseInterface() {
            @Override
            public void onClick(View view, StationNearBean bean) {
                //单元数据的点击事件 需要增加
                if (AMapUtil.isInstallByRead("com.autonavi.minimap")) {
                    Log.d("clark", "trip plan click metro");
                    AMapUtil.goToNaviActivity(TripPlanActivity.this, "test", null, bean.getLatitude() + "", bean.getLongitude() + "", "1", "2");
                } else {
                    Toast.makeText(TripPlanActivity.this, "请到应用市场下载高德地图", Toast.LENGTH_LONG).show();
                }
            }
        });
        LinearLayoutManager manager = new LinearLayoutManager(this);
        dataBinding.tripView2.setLayoutManager(manager);
        dataBinding.tripView2.setAdapter(tripPlanStationListAdapter);
        //地铁存在且第一个的时候可以刷新 处理滑动冲突
        dataBinding.tripView.setOnScrollListener(new RecyclerView.OnScrollListener(){
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int topRowVerticalPosition =
                        (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                swipeRefreshLayout.setEnabled(topRowVerticalPosition >= 0);
            }
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });


    }

    @Override
    protected void updateViews() {

    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.trip_des) {
            JumpUtils.jump(this, Constants.WHERETO, 0);
        } else if (id == R.id.trip_metro) {
            JumpUtils.jump(this, "SubwayHomeActivity", 0);
        } else if (id == R.id.trip_bus) {
            JumpUtils.jump(this, "BusHomeActivity", 0);
        } else if (id == R.id.trip_collect) {
            JumpUtils.jump(this, "busCollectActivity", 0);
        } else if (id == R.id.back) {
            finish();
        }

    }

    @Override
    public void getBusNearStationSuc(QueryNearStandbyRes queryNearStandbyRes) {
//        synchronized (this) {
//            //处理成统一的元素类对象
//            for (QueryNearStandbyRes.BusSiteListBean bean : queryNearStandbyRes.getBusSiteList()) {
//                StationNearBean station = new StationNearBean();
//                List<String> listLable = new ArrayList<>();
//                station.setStationName(bean.getStand_name());
//                station.setType("bus");
//                station.setStationAddress(bean.getRoad());
//                for (QueryNearStandbyRes.BusSiteListBean.BusInfosBean busInfosBean : bean.getBusInfos()) {
//                    if(!StringUtils.isEmpty(busInfosBean.getLine_name())){
//                        listLable.add(busInfosBean.getLine_name());
//                    }
//                }
////添加的为了统一list暂时没有用到
//                station.setLabelList(listLable);
//                station.setLatitude(bean.getLatitude());
//                station.setLongitude(bean.getLongitude());
//                listStationNear.add(station);
//            }
//            tripPlanStationListAdapter.setViewData(listStationNear);
//            tripPlanStationListAdapter.notifyDataSetChanged();
//
//        }
        tripPlanBusAdapter.setViewData(queryNearStandbyRes);
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        if(queryNearStandbyRes.getBusSiteList().size()>0){
            dataEmpty=false;
        }
       if(dataEmpty){
           dataBinding.llNoStation.setVisibility(View.VISIBLE);
       }else {
           dataBinding.llNoStation.setVisibility(View.GONE);
       }
    }

    @Override
    public void getSubwayNearStationSuc(QueryNearMetroStandbyRes queryNearMetroStandbyRes) {
//        synchronized (this) {
//            for (QueryNearMetroStandbyRes.MetroSiteListBean bean : queryNearMetroStandbyRes.getMetroSiteList()) {
//                StationNearBean station = new StationNearBean();
//                List<String> listLable = new ArrayList<>();
//                station.setStationName(bean.getStandName());
//                station.setType("metro");
//                station.setStationAddress(bean.getStandAddress());
//                String[] label = bean.getCrossLineName().split(",");
//                for (int i = 0; i < label.length; i++) {
//                    listLable.add(label[i]);
//                }
//                station.setLabelList(listLable);
//                station.setLatitude(bean.getLatitude());
//                station.setLongitude(bean.getLongitude());
//                listStationNear.add(station);
//            }
//            tripPlanStationListAdapter.setViewData(listStationNear);
//            tripPlanStationListAdapter.notifyDataSetChanged();
//        }
        tripPlanSubwayAdapter.setViewData(queryNearMetroStandbyRes);
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        if(queryNearMetroStandbyRes.getMetroSiteList().size()>0){
            dataEmpty=false;
        }
        if(dataEmpty){
            dataBinding.llNoStation.setVisibility(View.VISIBLE);
            swipeRefreshLayout.setEnabled(true);
        }else {
            dataBinding.llNoStation.setVisibility(View.GONE);
        }
    }

    public Context getActivity() {
        return TripPlanActivity.this;
    }

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }
    @Override
    public void onResume() {
        super.onResume();

    }
    @Override
    protected void onDestroy(){
        super.onDestroy();
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event.getCode() == MessageEvent.CODE_LOCTION) {
            EventBus.getDefault().unregister(this);
            mPresenter.getBusNearStation();
            mPresenter.getSubwayNearStation();
        }
    }
}